/*
 * Copyright (c) 2001 Sun Microsystems, Inc.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in
 * the documentation and/or other materials provided with the
 * distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 * if any, must include the following acknowledgment:
 * "This product includes software developed by the
 * Sun Microsystems, Inc. for Project JXTA."
 * Alternately, this acknowledgment may appear in the software itself,
 * if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA"
 * must not be used to endorse or promote products derived from this
 * software without prior written permission. For written
 * permission, please contact Project JXTA at http://www.jxta.org.
 *
 * 5. Products derived from this software may not be called "JXTA",
 * nor may "JXTA" appear in their name, without prior written
 * permission of Sun.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of Project JXTA.  For more
 * information on Project JXTA, please see
 * <http://www.jxta.org/>.
 *
 * This license is based on the BSD license adopted by the Apache Foundation.
 *
 * $Id: GroupJoinAction.java,v 1.5 2006/06/02 16:52:55 nano Exp $
 */

package net.jxta.myjxta.ui.action;

import net.jxta.credential.AuthenticationCredential;
import net.jxta.exception.PeerGroupException;
import net.jxta.exception.ProtocolNotSupportedException;
import net.jxta.membership.InteractiveAuthenticator;
import net.jxta.membership.MembershipService;
import net.jxta.myjxta.View;
import net.jxta.myjxta.ui.ChatFrame;
import net.jxta.myjxta.ui.GroupJoinPanel;
import net.jxta.myjxta.ui.MyJXTAView;
import net.jxta.myjxta.util.Group;
import net.jxta.myjxta.util.Resources;
import net.jxta.myjxta.util.objectmodel.GroupNode;
import net.jxta.peergroup.PeerGroup;
import net.jxta.protocol.PeerGroupAdvertisement;

import javax.swing.*;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.util.ResourceBundle;

/**
 * @author james todd [gonzo at jxta dot org]
 * @author mike mcangus [mcangus at jxta dot org]
 * @version $Id: GroupJoinAction.java,v 1.5 2006/06/02 16:52:55 nano Exp $
 */

public final class GroupJoinAction
        extends AbstractAction {

    private static final ResourceBundle STRINGS = Resources.getStrings();

    private View view = null;
    private MyJXTAView m_view = null;


    /**
     * Creates a new GroupJoinAction object.
     *
     * @param name The text to be used to describe this action.
     * @param view The view in which this action is to be performed.
     */
    public GroupJoinAction(String name, View view, MyJXTAView m_view) {
        super(name);

        this.view = view;
        this.m_view=m_view;
    }

    /**
     * @inheritDoc
     */
    public void actionPerformed(ActionEvent ae) {
        GroupNode gn = (GroupNode) this.view.getJxtaNode(GroupNode.class);
        Group g = gn != null ? gn.getGroup() : null;

        if (g != null) {
            Group p = g.getParentGroup();

            // xxx: not sure parent must be joined
            if (! g.isJoined() &&
                    p.isJoined()) {
                PeerGroupAdvertisement pga = g.getPeerGroupAdvertisement();

                //newGroup(PeerGroupID gid, Advertisement impl, String name, String description)
                try {
                    joinGroup(g, p.getPeerGroup().newGroup(pga));
                } catch (IllegalStateException ise) {
                    // handled in encompassing if statement
                } catch (PeerGroupException pge) {
                    this.view.setStatus(STRINGS.getString("error.group.create") +
                            " " + g.getName() + " " + pge.getMessage());
                }
            } else {
                this.view.setStatus(STRINGS.getString("error.group.joined") +
                        " " + g.getName() + " " + g.isJoined());
            }
        } else {
            this.view.setStatus(STRINGS.getString("error.group.create"));
        }
    }

    private void joinGroup(Group g, PeerGroup pg)
            throws PeerGroupException {
        MembershipService ms = pg.getMembershipService();

        if (ms.getDefaultCredential() == null) {
            signIn(g, pg);
        } else {
            process(g, pg);
        }
    }

    private void signIn(final Group g, final PeerGroup pg)
            throws PeerGroupException {
        MembershipService ms = pg.getMembershipService();
        AuthenticationCredential authCred =
                new AuthenticationCredential(pg, "DialogAuthentication", null);
        InteractiveAuthenticator auth;

        try {
            auth = (InteractiveAuthenticator) ms.apply(authCred);

            if (auth.interact() && auth.isReadyForJoin()) {
                ms.join(auth);
            }
        } catch (ProtocolNotSupportedException failed) {
            final JDialog jd = new JDialog((Frame) this.view,
                    STRINGS.getString("title.group.join") + " " +
                            pg.getPeerGroupName(), false);
            final GroupJoinPanel gj = new GroupJoinPanel(pg);

            jd.getContentPane().add(gj);
            jd.pack();
            jd.setLocationRelativeTo((Frame) this.view);
            jd.addComponentListener(new ComponentAdapter() {
                public void componentHidden(ComponentEvent ce) {
                    if (! gj.isCancel() &&
                            gj.isAuthorized()) {
                        process(g, pg);
                    }

//                    dialog = null;
//                    gj = null;
                }
            });
            jd.setVisible(true);
        }
    }

    private void process(Group g, PeerGroup pg) {
        g.setPeerGroup(pg);

        this.view.getControl().joinGroup(g, true, true);
        
        this.m_view.getRunButton().setEnabled(true);
    	
    	if(!ChatFrame.isVisible){

    		
    		JPanel p = new JPanel();
            GridBagLayout gb = new GridBagLayout();
            GridBagConstraints gbc = new GridBagConstraints();

            p.setLayout(gb);


            gbc.gridx = 0;
            gbc.gridy = 0;
            gbc.gridwidth = GridBagConstraints.REMAINDER;
//            gbc.insets = new Insets(3, 3, 3, 3);
            gbc.anchor = GridBagConstraints.NORTHWEST;
            gbc.weightx = 1.0;
            gbc.weighty = 1.0;
            gbc.fill = GridBagConstraints.BOTH;

            gb.setConstraints(this.m_view.plugins, gbc);
            p.add(this.m_view.plugins);
    		  		
    		ChatFrame cf=new ChatFrame(p);
            cf.setVisible(true);
		}
    }
}
